import React, { useEffect, useState } from 'react';
import { Descriptions, Modal, Divider, Button, Spin } from 'antd'
import { getOffHospitalDetail, submitOffHospitalPay } from '@/services/order/api';
import { showMsg, groupBy, isNull, print, isExits } from '@/utils/utils';
// @ts-ignore
import QRCode from 'qrcode.react';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import PermissionControl from '@/components/PermissionControl'
import Print from './Print';

const Detail: React.FC<any> = (props) => {
  const { 
    record = null,
    patientInfo = {}, 
    handleModalVisible,
    handleSettle,
    optCallback,
    type
  } = props;

  // 详情
  const [detail, setDetail] = useState<any>({});
  const [loading, setLoading] = useState(false);
  const [printing, setPrinting] = useState(false); // 是否打印

  // 合并行
  const hb = (value: any, record1: any, index: number, key?: string, valueEnum?: Object) => {
    const obj: any = {
      children: valueEnum || value,
      props: {},
    };
    if (index > 0) {
      const before = detail.record_list[index - 1]; // 前一行
      if (before?.order_id === record1.order_id) {
        // 与前一行相同，那当前就是被合并的行
        obj.props.rowSpan = 0;
        return obj;
      }
    }
    
    // 计算需要合并多少行
    const afterDataArr = detail.record_list.slice(index + 1);
    let count = 0;
    for (let i = 0, len = afterDataArr.length; i < len; i++) {
      const tmp = afterDataArr[i];
      if (tmp.order_id === record1.order_id) {
        count += 1;
      } else {
        break;
      }
    }
    if (count === 0) {
      return obj;
    }
    obj.props.rowSpan = count + 1;
    return obj;
  }

  const columns: ProColumns<any>[] = [
    {
      title: '账单类型',
      dataIndex: 'order_type',
      valueType: 'select',
      valueEnum: {
        P: '计划订单',
        O: '一次性订单',
        R: '租赁订单' 
      },
      render: (value, record1, index) => {
        return type === 'bill' ? value : hb(record1.order_type, record1, index, 'order_type', value)
      },
    },
    {
      title: '账单日期',
      dataIndex: 'bill_date',
      render: (value, record1, index) => {
        return type === 'bill' ? value : hb(value, record1, index, 'bill_date')
      },
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name'
    },
   
    {
      title: '规格（单位）',
      dataIndex: 'specs_name',
      render: (val, record1) => record1.order_type === 'R' ? '-' : val
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      valueType: 'money',
      align: 'right'
    },
    {
      title: '用量',
      dataIndex: 'goods_num'
    },
   
    {
      title: '折扣',
      dataIndex: 'discount',
      hideInTable: type === 'sett',
    },
    {
      title: '账单费用',
      dataIndex: 'bill_price',
      valueType: 'money',
      align: 'right',
      hideInTable: type === 'sett',
    },
    {
      title: '商品折扣',
      dataIndex: 'discount',
      align: 'right',
      hideInTable: type === 'bill',
    },
    {
      title: '账单金额',
      dataIndex: 'bill_price',
      valueType: 'money',
      align: 'right',
      hideInTable: type === 'bill',
    },
    {
      title: '账单折扣',
      dataIndex: 'order_discount',
      align: 'right',
      hideInTable: type === 'bill',
      render: (value, record1, index) => {
        return hb(value, record1, index, 'order_discount')
      },
    },
    {
      title: '结算金额',
      dataIndex: 'order_sett_price',
      valueType: 'money',
      align: 'right',
      hideInTable: type === 'bill',
      render: (value, record1, index) => {
        return hb(value, record1, index, 'order_sett_price')
      },
    }
  ]

  const getDetail = async (flag) => {
    let params = {
      patient_id: patientInfo.patient_id,
      admission_num: patientInfo.visit_no,
      current: 1,
      pageSize: 10000,
      order_id: record.order_id,
      manager_order_id: record.manager_order_id,
    }
    if (record.order_id) {
     delete params.manager_order_id
    } else {
     delete params.order_id
    }
    console.log(params);
    
    setLoading(true);
    const data = getOffHospitalDetail({
      ...params
    }).then((data) => {
      setDetail(Object.assign({}, data));
      setLoading(false);
      try {
        if (flag === 'refresh') {
          document.getElementsByClassName('ant-modal-body')[0].scrollTo(0, 100000)
        }
      } catch (error) {
        setLoading(false);
        console.log('error', error)
        // showMsg(error?.data?.errmsg);
      }
    }).catch(error => {
      showMsg(error?.data?.errmsg);
    });
    // // 先按账单日期排序，再按订单号排序
    // const arr = (data.record_list || []).sort(function(a,b){
    //   if (a.bill_date === b.bill_date) {
    //     return b.order_id - a.order_id
    //   }
    //   return b.bill_date - a.bill_date
    // })
    // console.log('arr', arr)
    // data.record_list = arr;
  }

  useEffect(() => {
    if (patientInfo.patient_id && record) {
      getDetail();
    }
  }, [patientInfo, record]);

  // 获得支付状态
  const getStatus = (key) => {
    switch (key) {
      case 'C': return '开单';
        
      case 'E': return '作废';
        
      case 'W': return '支付处理中';
        
      case 'P': return '已支付';
        
      case 'R': return '已退款';
        
      case 'U': return '退款处理中';
        
      case 'F': return '已作废';
            
      default: return '未知';
        
    }
  }

  return (
  <div>
    <Modal
      title="查看账单"
      wrapClassName="bill-modal"
      width="90%"
      bodyStyle={{ height: window.innerHeight-185, overflow: 'scroll' }}
      maskClosable={false}
      onCancel={() => handleModalVisible(false)}
      footer={[
        <Button key="back" onClick={() => { handleModalVisible(false) }}>
          关闭
        </Button>,
        (record.order_id && isExits('400404002')) &&
        <Button key="print" type="primary" onClick={() => {
          optCallback?.()
        }}>
          打印
        </Button>,
        
        (record.manager_order_id && (detail.pay_status === 'W' || detail.pay_status === 'P') && isExits('400404002'))  && 
        <Button key="print_settle" type="primary" onClick={() => {
          // printSettle();
          setPrinting(true);
        }}>
          打印结算单
        </Button>,

        detail.pay_status === 'W' &&
        <Button loading={loading} key="refresh" type="primary" onClick={() => getDetail('refresh')}>
          刷新
        </Button>,

        detail.manager_order_id && detail.pay_status === 'C' && 
        <PermissionControl action_id="400404006">
          <Button loading={loading} style={{ marginLeft: 8 }} key="start_settle" type="primary" onClick={ async () => { 
            try {
              setLoading(true);
              const data = await submitOffHospitalPay(record.manager_order_id);
              handleSettle?.(data);
              getDetail('refresh');
              setLoading(false);
            } catch (error) {
              setLoading(false);
              showMsg(error?.data?.errmsg)
            }
          }}> 
            发起结算
          </Button>
        </PermissionControl>
      ]}
      visible>
      <div className="order-modal-content">
        <div className='common_title'>1.患者信息</div>
        <Divider style={{margin: '10px 0'}} />
        <Descriptions column={4}>
          <Descriptions.Item label="身份证/住院号" span={2}>{patientInfo.identity_no} / {patientInfo.admission_num}</Descriptions.Item>
          <Descriptions.Item label="患者姓名">{patientInfo.patient_name}</Descriptions.Item>
          <Descriptions.Item label="归属科室">{patientInfo.admission_dept_name || patientInfo.admission_dept_code}</Descriptions.Item>
        </Descriptions>
       
        <div className='common_title'>2.商品信息</div>
        <Divider />
        <ProTable<any> 
          rowKey={() => {
            return (Math.random() * 10000).toFixed(2)
          }}
          style={{ marginTop:10 }}
          columns={columns}
          pagination={false}
          search={false}
          options={false}
          dataSource={detail.record_list || []}
          bordered />

        <div className='common_title'>3.汇总信息</div>
        <Divider style={{margin: '10px 0'}} />
        {
          record.order_id ? <Descriptions column={4}>
            <Descriptions.Item label="商品数量">
              <span style={{color: '#F5232D', fontWeight: 'bold'}}>{detail.total_goods_num}（件）</span>
            </Descriptions.Item>
            <Descriptions.Item label="总价">{detail.total_price}（元）</Descriptions.Item>
            <Descriptions.Item label="折扣">
              <span style={{color: '#F5232D', fontWeight: 'bold'}}>{parseFloat(parseFloat(detail.total_sett_price) / parseFloat(detail.total_price)).toFixed(2)}</span>
            </Descriptions.Item>
            
            <Descriptions.Item label="结算价">
              <span style={{color: '#F5232D', fontWeight: 'bold'}}>{detail.total_sett_price}</span>（元）
            </Descriptions.Item>
          </Descriptions> : 
          <Descriptions>
            {
              (!isNull(detail.settle_no) && detail.pay_status !== 'C' && detail.pay_status !== 'F') && <Descriptions.Item label="结算单号">{detail.settle_no}</Descriptions.Item>
            }
            <Descriptions.Item label="创建时间">{(detail.create_date ?? '') + ' ' + (detail.create_time ?? '')}</Descriptions.Item>
            {
              (detail.pay_qr_code_url && detail.pay_status === 'W') && <Descriptions.Item  label="微信/支付宝扫码支付">
                <QRCode
                  // value参数为生成二维码的链接
                  value={detail.pay_qr_code_url || ''}  
                  // 二维码的宽高尺寸
                  size={80} 
                  // 二维码的颜色
                  fgColor="#000"  
                  renderAs="svg"
                />
              </Descriptions.Item>
            }
            
            {
              detail.pay_time && <Descriptions.Item label="支付时间">{detail.pay_time}</Descriptions.Item>
            }
            <Descriptions.Item label="商品数量">
              <span style={{color: '#F5232D', fontWeight: 'bold'}}>{detail.total_goods_num}（件）</span>
            </Descriptions.Item>
            <Descriptions.Item label="总价">
              <span style={{color: '#F5232D', fontWeight: 'bold'}}>{detail.total_price}</span>（元）
            </Descriptions.Item>
            {
              detail.discount_ratio &&  <Descriptions.Item label="折扣">
                <span style={{color: '#F5232D', fontWeight: 'bold'}}>{detail.discount_ratio}</span>
              </Descriptions.Item>
            }
            <Descriptions.Item label="结算价">
              <span style={{color: '#F5232D', fontWeight: 'bold'}}>{detail.total_sett_price}</span>（元）
            </Descriptions.Item>
            <Descriptions.Item label="支付状态">
              {getStatus(detail.pay_status)}
            </Descriptions.Item>
          </Descriptions> 
        }
      </div>
    </Modal>
    {printing && <Print detail={detail} patientInfo={patientInfo} onFinish={() => setPrinting(false)} />}
  </div>
  )   
}
export default Detail;
